import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_harmony_order/api/order.dart';
import 'package:flutter_harmony_order/utils/auth.dart';
import 'components/order_tab_bar.dart';
import 'components/order_item.dart';

class OrderPage extends StatefulWidget {
  const OrderPage({super.key});

  @override
  State<OrderPage> createState() => _OrderPageState();
}

class _OrderPageState extends State<OrderPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final List<String> _tabs = ['全部', '待付款', '待发货', '待收货', '待评价'];
  final _platform = const MethodChannel('hdm_project');
  final ScrollController _scrollController = ScrollController();

  // 订单状态，1为待付款、2为待发货、3为待收货、4为待评价、5为已完成、6为已取消，未传该参数或0为全部
  Map<String, dynamic> params = {"orderState": 0, "page": 1, "pageSize": 10};
  List<Map<String, dynamic>> _orderList = [];
  bool _isLoading = false;
  bool _hasMore = true;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _tabs.length, vsync: this);
    _tabController.addListener(_handleTabChange);
    _scrollController.addListener(_handleScroll);
    _getToken();
  }

  void _handleTabChange() {
    if (_tabController.indexIsChanging) {
      setState(() {
        params["orderState"] = _tabController.index;
        params["page"] = 1;
        _orderList = [];
        _hasMore = true;
      });
      _getOrderList();
    }
  }

  void _handleScroll() {
    if (!_isLoading &&
        _hasMore &&
        _scrollController.position.pixels >=
            _scrollController.position.maxScrollExtent - 50) {
      _loadMore();
    }
  }

  Future<void> _loadMore() async {
    if (_isLoading) return;
    setState(() {
      _isLoading = true;
    });

    params["page"] = (params["page"] as int) + 1;
    try {
      final res = await getOrderListAPI(params);
      final newItems = List<Map<String, dynamic>>.from(res["items"]);

      setState(() {
        _orderList.addAll(newItems);
        _isLoading = false;
        _hasMore = newItems.isNotEmpty;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        params["page"] = (params["page"] as int) - 1;
      });
      _platform.invokeMethod("showMessage", e.toString());
    }
  }

  Future<void> _onRefresh() async {
    setState(() {
      params["page"] = 1;
      _hasMore = true;
    });
    await _getOrderList();
  }

  _getToken() async {
    TokenManager.token = await _platform.invokeMethod("getToken");
    if (!TokenManager.token.isEmpty) {
      _getOrderList();
    }
  }

  // 获取订单列表
  Future<void> _getOrderList() async {
    try {
      setState(() {
        _isLoading = true;
      });

      final res = await getOrderListAPI(params);
      final newItems = List<Map<String, dynamic>>.from(res["items"]);

      setState(() {
        _orderList = newItems;
        _isLoading = false;
        _hasMore = newItems.isNotEmpty;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      _platform.invokeMethod("showMessage", e.toString());
    }
  }

  @override
  void dispose() {
    _tabController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F5),
      body: Column(
        children: [
          OrderTabBar(
            tabs: _tabs,
            controller: _tabController,
          ),
          Expanded(
            child: RefreshIndicator(
              onRefresh: _onRefresh,
              color: const Color(0xFF333333),
              child: ListView.builder(
                controller: _scrollController,
                padding: const EdgeInsets.symmetric(horizontal: 12),
                itemCount: _orderList.length + 1,
                itemBuilder: (context, index) {
                  if (index == _orderList.length) {
                    return _buildLoadingIndicator();
                  }
                  return OrderItem(
                    orderInfo: _orderList[index],
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildLoadingIndicator() {
    if (!_hasMore) {
      return const Padding(
        padding: EdgeInsets.symmetric(vertical: 20),
        child: Center(
          child: Text(
            '没有更多数据了',
            style: TextStyle(
              color: Color(0xFF999999),
              fontSize: 12,
            ),
          ),
        ),
      );
    }

    if (_isLoading) {
      return const Padding(
        padding: EdgeInsets.symmetric(vertical: 20),
        child: Center(
          child: SizedBox(
            width: 24,
            height: 24,
            child: CircularProgressIndicator(
              strokeWidth: 2,
              valueColor: AlwaysStoppedAnimation(Color(0xFF333333)),
            ),
          ),
        ),
      );
    }

    return const SizedBox();
  }
}
